<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/8/10
 * Time: 09:58:53
 */

namespace Service\WebSocketService;

use App\Model\BbcModel\GoodsBrand;
use App\Model\BbcModel\GoodsImportLog;
use App\Model\BbcModel\ManagerChannel;
use PhpOffice\PhpSpreadsheet\Calculation\Web\Service;
use Service\Code\Normal;
use Hyperf\DbConnection\Db;
use Service\ExportService\ExportExcelHandle;

class GoodsBrandService extends \Service\BaseService
{
    /**
     * 品牌导入
     * @param $server
     * @param int $fd
     * @param array $body
     * @param int $manager_id
     * @param int $cid
     * @return array
     */
    public function import($server, int $fd, array $body, int $manager_id, int $cid)
    {
        if (empty($body['isUploadFile'])) {
            return Normal::returnCode(Normal::WS_ERROR, '需上传文件');
        }
        if (empty($body['fileUrl'])) {
            return Normal::returnCode(Normal::WS_ERROR, '上传到oss的文件链接为空');
        }
        if (empty($body['upLoadData'])) {
            return Normal::returnCode(Normal::WS_ERROR, '上传的文件数据为空');
        }
        $originFileUrl  = $body['fileUrl'];
        $pathInfo       = pathinfo($originFileUrl);
        $originFileName = $pathInfo['filename'] ?? $pathInfo['basename'];
        $list           = $body['upLoadData'];
        $managerInfo    = $this->managerInfo($manager_id);

        //去除空行数据
        foreach ($list as $key => $item) {
            $checkCol = array_filter($item);
            if (empty($checkCol) || empty(reset($item))) {
                unset($list[$key]);
            }
        }
        if ($server) {
            $send = Normal::returnCode(Normal::WS_START, "进行中", [
                'percent' => 5,
            ]);
            $server->push($fd, json_encode($send, JSON_UNESCAPED_UNICODE));
        }

        $all_list = GoodsBrand::instance()
            ->where(['cid'=>$cid,'df'=>0])
            ->select(['id','name'])
            ->get()->toArray();
        $all_list_map = array_column($all_list,null,'name');

        $errorData = [];
        $saveData  = [];
        $timeStp   = time();

        //去除表头
        array_shift($list);

        $saveData = [];
        $errorData = [];
        foreach ($list as $k=>$v){
            if(!$v[0]){
                continue;
            }
            if(isset($all_list_map[$v[0]])){
                $v[] = '品牌名称已存在';
                $errorData[] = $v;
                continue;
            }
            $saveData[$k]['sid'] = $managerInfo['sid'];
            $saveData[$k]['cid'] = $managerInfo['cid'];
            $saveData[$k]['type'] = 2;
            $saveData[$k]['name'] = $v[0];
            $saveData[$k]['info'] = empty($v[1]) ? '' : $v[1];
            $saveData[$k]['sort'] = empty($v[2]) ? '' : $v[2];
            $saveData[$k]['md'] = $timeStp;
            $saveData[$k]['cd'] = $timeStp;
        }

        Db::beginTransaction();
        try{
            if(count($errorData) > 0){ //有错误数据
                $fileName  = "品牌导入错误信息.xlsx";
                $headArr   = ['品牌名称','描述','排序','错误信息'];
                $exportRes = ExportExcelHandle::instance()->uploadAliOssSource($fileName, $headArr, $errorData);
                if ($exportRes['code'] != Normal::SUC) {
                    return Normal::returnCode(Normal::WS_ERROR, '上传错误导入信息失败：'.$exportRes['msg']);
                }
                $download_url = $exportRes['data']['path'];
            }

            if(count($saveData) > 0){ //有正确的导入数据
                GoodsBrand::instance()
                    ->insert($saveData);
            }


            //保存到导入日志
            $all_num = count($list) - 1;
            $count = count($saveData);
            $importLog = [
                'file_name'       => $originFileName,
                'import_type'     => 1,
                'all_num'         => $all_num,
                'success_num'     => $count,
                'fail_num'        => 0,
                'status'          => 1,
                'origin_file_url' => $originFileUrl,
                'fail_file_url'   => $download_url ?? '',
                'manager_id'      => $manager_id,
                'manager_name'    => $managerInfo['name'],
                'cd'              => $timeStp,
                'md'              => $timeStp,
            ];
            GoodsImportLog::instance()->insert($importLog);
            Db::commit();
        }catch (\Exception $e){
            Db::rollBack();
            return Normal::returnCode(Normal::WS_ERROR,'导入失败:'.$e->getMessage());
        }

        return Normal::returnCode(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $download_url ?? [],
        ]);
    }

    /**
     * 获取后台操作人员信息
     */
    public function managerInfo($manager_id) {
        return ManagerChannel::instance()->info(['id' => $manager_id]);
    }

    public function export($server, int $fd, array $body, int $manager_id, int $cid){
        ini_set('memory_limit', '3096M');
        $param        = $body;
        $param['cid'] = $cid;
        $whereRaw     = (new \Service\CommodityService\GoodsBrandService())::instance()->makeWhere($param);
        if ($server) {
            $send = Normal::returnCode(Normal::WS_START, "进行中", [
                'percent' => 20,
            ]);
            $server->push($fd, json_encode($send, JSON_UNESCAPED_UNICODE));
        }

        $data_list = GoodsBrand::instance()
            ->where($whereRaw)
            ->select(['id','name','info','sort'])
            ->get()->toArray();
        if (!$data_list) {
            return Normal::returnCode(Normal::WS_ERROR, '数据为空');
        }


        $data['header'] = [
            'id', '品牌名称', '描述', '排序'
        ];

        $data['fileName'] = '商品品牌.xlsx';
        $data['data']     = $data_list;
        $exportRes        = ExportExcelHandle::instance()->uploadAliOssSource($data['fileName'], $data['header'], $data['data']);
        if ($exportRes['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::WS_ERROR, '导出失败:' . $exportRes['msg']);
        }
        return Normal::returnCode(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $exportRes['data']['path'],
        ]);
    }
}